//确认订单
import React, {Component} from 'react';
import styles from '../style/styles';
import Header from '../common/header';
import Icon from 'react-native-vector-icons/Ionicons';
import Alipay from '../common/Alipay';//支付
import * as URLconstant from '../constant/URLconstant'
import Util from '../common/util'
import Toast from '../common/ToastUtil'
import Modal from 'react-native-modalbox'
import XPay from 'react-native-puti-pay'
import {
    View,
    Text,
    ScrollView,
    Image,
    TouchableOpacity,
    TextInput,
    DeviceEventEmitter,
    Switch,
    Platform
} from 'react-native';

export default class confirmOrder extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.errorCallback = this.errorCallback.bind(this)
        this.successGetgood = this.successGetgood.bind(this)
        this.successGelogisticst = this.successGelogisticst.bind(this)
        this.successGetAdd = this.successGetAdd.bind(this)
        this.toAddress = this.toAddress.bind(this)
        this.TO_alipay = this.TO_alipay.bind(this)
        this.successPostOrder = this.successPostOrder.bind(this)
        this.setDelivery = this.setDelivery.bind(this)
        this.iosAlipay = this.iosAlipay.bind(this)
        this.state = {
            delitype: ['天天快递', '顺非快递', '申通快递'],
            loaded: true,
            type: this.props.type,
            user_id: this.props.user_id,
            list: this.props.list,
            data: null,
            maininput: '',
            selectedLogistics: null,
            surplus: 0,//当前余额
            isUse: false,
            use_surplus: 0,//使用余额
            couponList: [],//可用优惠券列表
            selectCoupon: null,//选择使用的优惠券
            isOpen: false,//是否显示优惠券选择列表
        };
    }


    componentDidMount() {
        this.setParams()

        if (Platform.OS === 'android') {
            if (this.payListener == undefined) {
                this.payListener = DeviceEventEmitter.addListener('keyboardWillShow', function (Event) {
                    //LOG("Event=========="+JSON.stringify(Event));
                    let extras = Event.extras;
                    let alertContent = Event.alertContent;
                    if (extras == 9000) {
                        let data = that.state.data;
                        if (data.isPin == 1) {
                            let params = that.props.route.params
                            params.getIndexAgain()
                            DeviceEventEmitter.emit('buyGroup')
                        }
                    }
                    LOG('pop=====' + 3)
                    that.props.navigation.pop();
                });
            }
        }
    }

    getOrder() {
        let that = this
        let type = this.state.type;
        let user_id = this.state.user_id;
        let datakey = []
        this.getSurplus()
        if (type == 1) {
            let list = this.state.list
            datakey['user_id'] = user_id;
            datakey['shopping_id_num'] = list;
            let getGoodsurl = URLconstant.GETCARTGOODS_URL;
            Util.get(getGoodsurl, datakey, this.successGetgood, this.errorCallback)
        } else {
            let datakey = [];
            let MESSAGE_URL
            let data = this.state.data;
            let spec_id = data.spec_id;
            let buyNum = data.buyNum;
            let goods_id = data.goods_id;
            let shop_id = data.shop_id
            let isBox = data.isBox
            let isPin = data.isPin
            let pin_id = data.pin_id
            if (isPin == 1) {
                datakey['user_id'] = user_id
                datakey['pintuan_id'] = pin_id
                datakey['goods_id'] = goods_id
                datakey['quantity'] = buyNum
                datakey['spec_id'] = spec_id
                MESSAGE_URL = URLconstant.GROUP_BUY;
            } else {
                MESSAGE_URL = URLconstant.BUYATONCE_URL;
                datakey['goods_id'] = goods_id;
                datakey['quantity'] = buyNum;
                datakey['user_id'] = user_id;
                datakey['spec_id'] = spec_id;
                datakey['shop_id'] = shop_id
                datakey['is_means'] = isBox
            }
            Util.get(MESSAGE_URL, datakey, this.successGetgood, this.errorCallback);

        }
    }

    async setParams() {
        let params = this.props.route.params
        if (params.user_id) {
            await this.setState({
                user_id: params.user_id
            })
        }
        if (params.type) {
            await this.setState({
                type: params.type
            })
        }
        if (params.list) {
            await this.setState({
                list: params.list
            })
        }
        if (params.data) {
            await this.setState({
                data: params.data
            })
        }
        this.getOrder()
    }


    getCoupon() {
        let url = URLconstant.MY_COUPON
        let datakey = []
        datakey['user_id'] = this.state.user_id
        Util.get(url, datakey, this.getCouponSuc.bind(this), this.errorcallback.bind(this))
    }

    getCouponSuc(datas) {
        let couponList = []
        let orderData = this.state.data;
        let total = orderData.total;
        if (datas.status == 0) {
            let data = datas.data
            for (let item of data) {
                let timestamp = Date.parse(new Date()) / 1000
                if (item.end_time > timestamp && item.order_id == 0 && item.used_time == 0 && item.min_goods_order <= total.goods_amount) {
                    couponList.push(item)
                }
            }
        }
        this.setState({
            couponList: couponList
        })
    }

    componentWillUnmount() {
        LOG('pop====' + 4)
        if (Platform.OS === 'android') {
            this.payListener.remove();
        }
    }


    getSurplus() {
        let datakey = []
        datakey['user_id'] = this.state.user_id;
        let url = URLconstant.USERINFO_URL;
        Util.get(url, datakey, this.getSurplusSuc.bind(this), this.errorcallback.bind(this));
    }

    getSurplusSuc(datas) {
        if (datas.status == 0) {
            this.setState({
                surplus: datas.data.userInfo.surplus
            })
        }
    }

    errorcallback(err) {

    }

    successGetgood(datas) {
        LOG('=============' + JSON.stringify(datas))
        let data = datas.data;
        if (datas.status == 0) {
            this.setState({
                data: data,
            })
            this.getAddress()
            this.getUseSurplus()
            this.getCoupon()
        } else {
            Toast.show(datas.msg)
            this.props.navigation.pop()

        }


    }


    errorCallback(err) {
        LOG(err)
    }

    getLogistics(addr_id) {
        let logisticsUrl = URLconstant.SHIPPING_LIST
        let datakey = [];
        let data = this.state.data
        datakey['t'] = 1
        datakey['addr_id'] = addr_id;
        datakey['goods_amount'] = data.total.goods_amount
        datakey['goods_num'] = data.total.quantity
        Util.get(logisticsUrl, datakey, this.successGelogisticst, this.errorCallback)
    }


    successGelogisticst(datas) {
        //LOG('11111'+JSON.stringify(datas))
        let logdata = datas.data;
        this.setState({
            logdata: logdata,
        })

    }

    //修改地址后返回刷新
    componentWillReceiveProps(nextProps) {
        this.getAddress()
    }


    getAddress() {
        let user_id = this.state.user_id;
        let url = URLconstant.ADDRESSADMIN_URL;
        let datakey = [];
        datakey['onli'] = '1'
        datakey['user_id'] = user_id;
        Util.get(url, datakey, this.successGetAdd, this.errorCallback)
    }


    successGetAdd(datas) {
        //LOG(JSON.stringify(datas))
        if (datas.status == 0) {
            let data = datas.data;
            let address = data;
            this.setState({
                address: address,
                loaded: false,
            })
            this.getLogistics(address.addr_id)
        } else {
            this.setState({
                address: '',
                loaded: false,
            })
            Toast.show(datas.msg)
        }
    }

    toAddress() {
        let that = this;
        that.props.navigation.push('AddressAdmin')
    }


    //默认收货地址
    userAddress() {
        let address = this.state.address;
        return (
            <TouchableOpacity onPress={() => this.toAddress()}>
                <View style={{
                    flexDirection: 'row',
                    paddingHorizontal: 15,
                    paddingVertical: 15,
                    alignItems: 'center',
                    backgroundColor: "#fff"
                }}>
                    <View style={{flex: 1, paddingRight: 10}}>
                        <View style={{flexDirection: "row", marginBottom: 10}}>
                            <Text style={{fontSize: 14, color: "#333", marginRight: 10}}>{address.consignee}</Text>
                            <Text style={{fontSize: 14, color: "#333"}}>{address.phone_mob}</Text>
                        </View>
                        <Text style={{fontSize: 12, color: "#969696"}}>{address.region_name} {address.address}</Text>
                    </View>
                    <Icon name={'ios-arrow-forward'} size={20} color={'#aaa'}/>
                </View>
                <Image
                    resizeMode="stretch"
                    style={styles.adr_bg}
                    source={require('../imgs/address_01.png')}/>
            </TouchableOpacity>
        )
    }


    showPrice(item) {
        if (item.type == 9) {
            price = item.cut_buy
            txt = '拼团价'
        } else {
            price = item.buy_price
            txt = '单价:'
        }
        return (
            <View style={styles.buy_num_wrap}>
                <Text>{txt}</Text>
                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <Text style={{fontSize: 12, color: "#ee1f12", marginRight: 2, marginTop: 4}}>¥</Text>
                    <Text style={{fontSize: 16, color: "#ee1f12", fontWeight: 'bold'}}>{price}</Text>
                </View>
            </View>
        )
    }

    //订单产品信息
    orderGoodsInfo() {
        let data = this.state.data;
        let goods_list = data.goods_list
        let list = [];
        let row;
        for (let i in goods_list) {
            row = (
                <View key={i}>
                    <View style={{
                        flexDirection: 'row',
                        marginTop: 10,
                        height: 40,
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        paddingHorizontal: 15,
                        backgroundColor: "#fff"
                    }}>
                        <Text style={{fontSize: 16, color: "#ee1f12"}}>{goods_list[i].shop_name || '平台总'}仓</Text>
                        <View style={{
                            height: 20,
                            paddingHorizontal: 5,
                            justifyContent: 'center',
                            backgroundColor: "#ee1f12"
                        }}>
                            <Text style={{fontSize: 12, color: "#fff"}}>现货</Text>
                        </View>
                    </View>
                    <View style={styles.order_goods_wrap}>
                        <View style={{width: 80, height: 80}}>
                            <Image
                                resizeMode="stretch"
                                style={{width: 80, height: 80}}
                                source={{uri: goods_list[i].goods_img}}/>
                        </View>
                        <View style={{flex: 1, paddingLeft: 10, height: 70, justifyContent: 'space-between'}}>
                            <Text numberOfLines={2}
                                  style={{fontSize: 14, color: "#000"}}>{goods_list[i].goods_name}</Text>
                            <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between'}}>
                                {goods_list[i].spec_id == 0 ?
                                    null
                                    :
                                    <Text style={styles.order_goods_pare}> {goods_list[i].specification}</Text>
                                }
                                <Text style={{fontSize: 16, color: "#969696", fontWeight: 'bold'}}><Text
                                    style={{fontSize: 12, fontWeight: 'normal'}}>x</Text>{goods_list[i].quantity}</Text>
                            </View>
                        </View>
                    </View>
                    {this.showPrice(goods_list[i])}
                </View>

            )
            list.push(row)

        }
        return list
    }

    selectDelivery() {
        this.props.navigation.push('SelectLogistics', {
            user_id: this.state.user_id,
            callback: (datas) => {
                this.setDelivery(datas)
            }
        })
    }


    //设置物流
    async setDelivery(datas) {
        LOG("datas===" + JSON.stringify(datas))
        let logdata = this.state.logdata
        for (let item of logdata) {
            if (item.shipping_id == datas.shipping_id) {
                if (datas.self_delivery == 1) {
                    item.delivery_type = datas.delivery_type
                    if (datas.delivery_type == 1) {
                        item.ship_time = datas.ship_time
                    }
                }
                LOG("item=====" + JSON.stringify(item))
                await this.setState({
                    selectedLogistics: item
                })
                this.getUseSurplus()
            }

        }

    }

    //配送方式
    deliveryMode() {
        let selectedLogistics = this.state.selectedLogistics
        return (
            <TouchableOpacity onPress={() => this.selectDelivery()} style={styles.deli_wrap}>
                <Text>配送信息</Text>
                {
                    selectedLogistics == null ?
                        <Text style={{fontSize: 14, color: "#696969"}}>请选择配送方式</Text>
                        :
                        <Text style={{fontSize: 14, color: "#000"}}>{selectedLogistics.shipping_name}</Text>
                }
            </TouchableOpacity>
        )
    }

    showCouponItem() {
        let couponList = this.state.couponList
        let selectCoupon = this.state.selectCoupon
        return (
            <View style={styles.deli_wrap}>
                <Text>选择优惠券</Text>
                {
                    couponList.length > 0 ?
                        <TouchableOpacity onPress={() => this.setState({isOpen: true})}>
                            <Text style={{
                                fontSize: 14,
                                color: "#000"
                            }}>{selectCoupon == null ? "有可用的优惠券" : '-' + selectCoupon.coupon_value}</Text>
                        </TouchableOpacity>
                        :
                        <Text style={{fontSize: 14, color: "#696969"}}>无可用优惠券</Text>
                }
            </View>
        )
    }

    //选择快递
    selectedExpress(item) {
        this.setState({
            selectedDeli: item,
        })
    }

    //获取快递信息
    getExpress() {
        let that = this;
        let logdata = this.state.logdata;
        let rows;
        let list = [];
        for (let i in logdata) {
            if (that.state.selectedDeli == logdata[i].shipping_id) {
                rows = (
                    <TouchableOpacity key={i} onPress={() => that.selectedExpress(logdata[i].shipping_id)}
                                      style={styles.express_choose}>
                        <Icon name={'md-checkmark-circle'} size={25} color="#f00"
                              style={styles.modal_cate_choose}/>
                        <Text style={styles.order_goods_header}>{logdata[i].shipping_name}</Text>
                    </TouchableOpacity>
                )
                list.push(rows);
            } else {
                rows = (
                    <TouchableOpacity key={i} onPress={() => that.selectedExpress(logdata[i].shipping_id)}
                                      style={styles.express_choose}>
                        <Icon name={'ios-radio-button-off-outline'} size={25} color="#666"
                              style={styles.modal_cate_choose}/>
                        <Text style={styles.order_goods_header}>{logdata[i].shipping_name}</Text>
                    </TouchableOpacity>
                )
                list.push(rows);
            }

        }
        return list;
    }

    //给卖家留言
    message() {
        return (
            <View style={styles.message_box}>
                <Text style={styles.message_title}>给卖家留言</Text>
                <View style={styles.message_wrap}>
                    <TextInput
                        style={styles.messge_input}
                        multiline={true}
                        placeholder={'意见反馈'}
                        underlineColorAndroid={'transparent'}
                        clearButtonMode={'always'}
                        onChangeText={(text) => this.setState({maininput: text})}
                    />
                </View>
            </View>
        )
    }

    TO_alipay(shipping_fee) {
        let data = this.state.data;
        let goods_list = data.goods_list
        let address = this.state.address;
        let addr_id = address.addr_id;
        let user_id = this.state.user_id;
        let list = this.state.list
        let shopping_id;
        if (list == null || list == '') {
            shopping_id = goods_list[0].shopping_id
        } else {
            shopping_id = list
        }
        let datakey = [];
        let selectedLogistics = this.state.selectedLogistics
        if (selectedLogistics == null) {
            Toast.show('请先选择配送物流')
            return false
        }
        LOG('selectedLogistics===' + JSON.stringify(selectedLogistics))
        let shipping_id = selectedLogistics.shipping_id
        LOG('shipping_id===' + shipping_id)
        let url = URLconstant.CONFIRM_ORDER_URL;
        if (shipping_id == null || shipping_id == '') {
            Toast.show('请先选择配送物流')
        } else if (addr_id == null || addr_id == '') {
            Toast.show('请先添加收货地址')
        } else {
            let propsData = this.state.data;
            LOG('propsData===' + propsData)
            if (selectedLogistics.self_delivery == 1) {
                datakey['delivery_type'] = selectedLogistics.delivery_type
                if (selectedLogistics.delivery_type == 1) {
                    datakey['appoitment_time'] = selectedLogistics.ship_time
                }
            }
            if (this.props.isKill == 1) {
                datakey['flow_type'] = 3
                datakey['spree_id'] = this.props.spree_id
            }
            if (propsData && propsData.isPin == 1) {
                datakey['flow_type'] = 9
                datakey['pintuan_id'] = propsData.pin_id
                datakey['spec_id'] = propsData.spec_id
                datakey['quantity'] = propsData.buyNum;
            }
            let isUse = this.state.isUse
            if (isUse) {
                datakey['surplus'] = this.state.use_surplus
            }
            let selectCoupon = this.state.selectCoupon
            if (selectCoupon) {
                datakey['coupon_id'] = selectCoupon.coupon_id
            }
            datakey['addr_id'] = addr_id;
            datakey['user_id'] = user_id;
            datakey['shipping_id'] = shipping_id;
            datakey['shipping_fee'] = shipping_fee;
            datakey['shopping_id_num'] = shopping_id;
            datakey['postscript'] = this.state.maininput
            datakey['pay_type'] = 2
            LOG("提交订单返回数据url==========" + url);
            Util.post(url, datakey, this.successPostOrder, this.errorCallback)
        }

    }

    successPostOrder(datas) {
        LOG("提交订单返回数据==========" + JSON.stringify(datas))
        if (datas.status == 0) {
            DeviceEventEmitter.emit('changeCart')
            let data = datas.data
            //LOG(JSON.stringify(data));
            let order_sn = data.order_sn;
            let order_name = '嘉艺画框';
            let order_amount = data.order_amount;
            let returnName = "keyboardWillShow";
            let alipaySign = datas.data.alipaySign
            XPay.setAlipayScheme('alipayJiayi')
            XPay.alipay(alipaySign,(res)=>this.payResult(res))
            //Alipay.alipayWithTradeNO(order_sn, order_name, order_amount, returnName, alipaySign, this.iosAlipay);
            //LOG('动')
        } else if (datas.status == 1) {
            Toast.show(datas.msg)
            LOG('pop=====' + 2)
            this.props.navigation.pop()
        } else {
            Toast.show(datas.msg)
        }
    }



    payResult(res){
        LOG('支付返回======>>>>>'+JSON.stringify(res))
        if (res.resultStatus == 9000) {
            let data = that.state.data;
            if (data.isPin == 1) {
                let params = that.props.route.params
                params.getIndexAgain()
                DeviceEventEmitter.emit('buyGroup')
            }
            Toast.show('支付成功')
        }else{
            Toast.show(res.memo)
        }
        this.props.navigation.pop();
    }

    iosAlipay(errot, datas) {
        let that = this;
        LOG('支付宝返回' + JSON.stringify(datas));
        let events = JSON.stringify(datas);
        let resultStatus = datas.resultStatus;
        Toast.show('支付成功')
        if (resultStatus == 9000) {
            if (that.pinData && that.props.isPin == 1) {
                let data = {}
                data.tuan_user_id = that.props.tuan_user_id
                data.pintuan_log_id = that.props.pintuan_log_id == 0 ? that.pinData.pintuan_log_id : that.props.pintuan_log_id
                data.pintuan_id = that.props.pin_id
                data.isBuy = true
                LOG('提交订单返回数据====' + JSON.stringify(data))
                that.props.buyRefresh(data)
            }
        } else {
            Toast.show(datas.memo)
        }
        this.props.navigation.pop()
    }


    confirmOrder() {
        let data = this.state.data;
        let total = data.total;
        return (
            <View style={styles.confirm_bottom}>
                <View></View>
                <TouchableOpacity style={styles.con_btn} onPress={() => this.TO_alipay(total.shipping_fee)}>
                    <Text style={styles.con_btn_txt}>提交订单</Text>
                </TouchableOpacity>
            </View>
        )
    }

    fixedNum(num) {
        return parseFloat(num).toFixed(2)
    }


    showSurplus() {
        return (
            <View style={{backgroundColor: "#fff", marginTop: 10}}>
                <View style={{
                    paddingHorizontal: 10,
                    height: 35,
                    alignItems: "center",
                    justifyContent: 'space-between',
                    flexDirection: 'row'
                }}>
                    <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: "center"}}>
                        <Text>当前余额: </Text>
                        <Text style={styles.con_red_txt}>¥{this.state.surplus}</Text>
                    </View>
                </View>
                <View style={{
                    paddingHorizontal: 10,
                    borderTopWidth: 1,
                    borderTopColor: "#e0e0e0",
                    height: 35,
                    alignItems: "center",
                    justifyContent: 'space-between',
                    flexDirection: 'row'
                }}>
                    <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: "center"}}>
                        <Text>可用余额抵扣: </Text>
                        <Text style={styles.con_red_txt}>¥{this.fixedNum(this.state.use_surplus)}</Text>
                    </View>
                    <Switch value={this.state.isUse} onValueChange={(value) => this.changeUse(value)}/>
                </View>
            </View>
        )
    }


    getUseSurplus() {
        let surplus = this.state.surplus
        let use_surplus
        let data = this.state.data;
        let total = data.total;
        let order_amount = total.goods_amount
        let selectedLogistics = this.state.selectedLogistics
        let shipping_quantity = total.shipping_quantity
        let shipping_first_price = 0
        let shipping_second_price = 0
        if (selectedLogistics != null && selectedLogistics.shipping_id != 1) {
            let first_unit = selectedLogistics.first_unit
            let continue_unit = selectedLogistics.continue_unit
            let first_price
            let continue_price
            if (selectedLogistics.self_delivery == 1) {
                first_price = selectedLogistics.first_area_price
                continue_price = selectedLogistics.continue_area_price
            } else {
                first_price = selectedLogistics.first_price
                continue_price = selectedLogistics.continue_price
            }
            shipping_first_price = first_price
            if (shipping_quantity > first_unit) {
                shipping_second_price = continue_price * Math.ceil((shipping_quantity - first_unit) / continue_unit)
            }
        }
        shipping_first_price = parseFloat(shipping_first_price)
        shipping_second_price = parseFloat(shipping_second_price)
        let selectCoupon = this.state.selectCoupon
        let couponPrice = 0
        if (selectCoupon != null) {
            couponPrice = parseFloat(selectCoupon.coupon_value)
        }
        let total_pay = order_amount + shipping_first_price + shipping_second_price - couponPrice
        if (parseFloat(surplus) > parseFloat(total_pay)) {
            use_surplus = total_pay
        } else {
            use_surplus = surplus
        }
        this.setState({
            use_surplus: use_surplus
        })
    }

    changeUse(isUse) {
        this.setState({
            isUse: isUse
        })
    }

    showOrderPrice() {
        let data = this.state.data;
        let total = data.total;
        let selectedLogistics = this.state.selectedLogistics
        let shipping_quantity = total.shipping_quantity
        let shipping_first_price = 0
        let shipping_second_price = 0
        if (selectedLogistics != null && selectedLogistics.shipping_id != 1) {
            let first_unit = selectedLogistics.first_unit
            let continue_unit = selectedLogistics.continue_unit
            let first_price
            let continue_price
            if (selectedLogistics.self_delivery == 1) {
                first_price = selectedLogistics.first_area_price
                continue_price = selectedLogistics.continue_area_price
            } else {
                first_price = selectedLogistics.first_price
                continue_price = selectedLogistics.continue_price
            }
            LOG('first_price===' + first_price, 'continue_price====' + continue_price)
            LOG('selectedLogistics====' + JSON.stringify(selectedLogistics))
            shipping_first_price = first_price
            if (shipping_quantity > first_unit) {
                shipping_second_price = continue_price * Math.ceil((shipping_quantity - first_unit) / continue_unit)
            }
        }

        shipping_first_price = parseFloat(shipping_first_price)
        shipping_second_price = parseFloat(shipping_second_price)
        let selectCoupon = this.state.selectCoupon
        let couponPrice = 0
        if (selectCoupon != null) {
            couponPrice = parseFloat(selectCoupon.coupon_value)
        }
        return (
            <View style={{
                alignItems: 'center',
                justifyContent: 'center',
                paddingVertical: 10,
                backgroundColor: "#f0f0f0"
            }}>
                <View style={{
                    alignItems: 'center',
                    justifyContent: 'center',
                    flexDirection: 'row',
                    marginBottom: 10,
                    flexWrap: 'wrap'
                }}>
                    <Text style={{fontSize: 14, color: "#000"}}>商品总计:¥{this.fixedNum(total.goods_amount)}</Text>
                    {
                        selectedLogistics == null || selectedLogistics.shipping_id == 1 ?
                            null :
                            <View style={{flexDirection: "row", alignItems: 'center', justifyContent: 'center'}}>
                                <Text style={{fontSize: 14, color: "#696969"}}> +
                                    ¥{this.fixedNum(shipping_first_price)}运费</Text>
                                <Text style={{fontSize: 14, color: "#696969"}}> +
                                    ¥{this.fixedNum(shipping_second_price)}续件费</Text>
                            </View>
                    }
                    {
                        couponPrice > 0 ?
                            <Text style={{fontSize: 14, color: "#696969"}}> -优惠券:¥{couponPrice}</Text> : null
                    }
                </View>
                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <Text style={{fontSize: 14, color: "#9e0a16", marginRight: 5}}>需付:</Text>
                    <Text style={{fontSize: 12, color: "#9e0a16", marginTop: 6}}>¥</Text>
                    <Text style={{
                        fontSize: 20,
                        color: "#9e0a16",
                        fontWeight: 'bold'
                    }}>{this.fixedNum(total.goods_amount + shipping_first_price + shipping_second_price - couponPrice)}</Text>
                </View>
            </View>
        )
    }

    returnTime(end_time) {
        let date = new Date(end_time * 1000)
        let year = date.getFullYear() + '-';
        let month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        let day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
        let hours = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ":"
        let minutes = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":"
        let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        let timeTxt = year + month + day + hours + minutes + seconds
        return timeTxt
    }

    async selectCoupon(item) {
        await this.setState({
            selectCoupon: item,
            isOpen: false
        })
        this.getUseSurplus()
    }

    async noUseCoupon() {
        await this.setState({
            selectCoupon: null,
            isOpen: false
        })
        this.getUseSurplus()
    }

    showCouponModal() {
        let couponList = this.state.couponList
        let selectCoupon = this.state.selectCoupon
        return (
            <Modal
                style={styles.coupon_modal}
                position={'bottom'}
                isOpen={this.state.isOpen}
                swipeToClose={false}
                onClosed={() => this.setState({isOpen: false})}
            >
                <View style={{alignItems: 'center', justifyContent: 'center', height: 40}}>
                    <Text style={{fontSize: 14, color: "#000"}}>请选择要使用的优惠券</Text>
                </View>
                <ScrollView style={{flex: 1}} contentContainerStyle={{alignItems: 'center'}}>
                    {
                        couponList.map((item, index) => {
                            return (
                                <TouchableOpacity onPress={() => this.selectCoupon(item)} key={index}
                                                  style={{
                                                      flexDirection: "row",
                                                      alignItems: 'center',
                                                      justifyContent: 'space-between',
                                                      width: Util.size.width,
                                                      paddingHorizontal: 10
                                                  }}>
                                    <View style={styles.coupon_item}>
                                        <Image
                                            source={require('../imgs/coupon_bg.png')}
                                            style={{width: Util.size.width - 60, height: (Util.size.width - 60) * 0.31}}
                                            resizeMode={'cover'}
                                        />
                                        <View style={styles.item_header}>
                                            <View style={styles.coupon_price_view}>
                                                <Text style={{
                                                    fontSize: 14,
                                                    color: "#fff",
                                                    marginTop: 7,
                                                    backgroundColor: "transparent"
                                                }}>¥</Text>
                                                <Text style={{
                                                    fontSize: 28,
                                                    color: "#fff",
                                                    backgroundColor: "transparent"
                                                }}>{item.coupon_value}</Text>
                                            </View>
                                            <Text style={{
                                                fontSize: 16,
                                                color: "#fff",
                                                backgroundColor: "transparent"
                                            }}>满{item.min_goods_order}可用</Text>
                                        </View>
                                        <View style={styles.item_bottom}>
                                            <Text style={{
                                                fontSize: 12,
                                                color: "#fff",
                                                backgroundColor: "transparent"
                                            }}>使用期限:{this.returnTime(item.end_time)}</Text>
                                        </View>
                                    </View>
                                    {
                                        selectCoupon != null && selectCoupon.coupon_id == item.coupon_id ?
                                            <Icon name={'ios-checkmark-circle'} size={30} color={'#ee1f12'}/> :
                                            <Icon name={'ios-checkmark-circle-outline'} size={30} color={'#333'}/>
                                    }
                                </TouchableOpacity>
                            )
                        })
                    }
                </ScrollView>
                <TouchableOpacity
                    onPress={() => this.noUseCoupon()}
                    style={{height: 40, alignItems: 'center', justifyContent: 'center', backgroundColor: "#ee1f12"}}
                >
                    <Text style={{fontSize: 14, color: "#fff"}}>本次不使用优惠券</Text>
                </TouchableOpacity>
            </Modal>
        )
    }

    render() {
        return (
            <View style={{flex: 1}}>
                <Header navigation={this.props.navigation} title={'确认订单'}/>
                {this.state.loaded ?
                    <View style={{flex: 1}}>
                        {Util.loading()}
                    </View>
                    :
                    <View style={{flex: 1}}>
                        <ScrollView style={styles.bg_scrollview}>
                            {this.userAddress()}
                            {this.deliveryMode()}
                            {this.showCouponItem()}
                            {this.orderGoodsInfo()}
                            {/*{this.showSurplus()}*/}
                            {this.message()}
                        </ScrollView>
                        {this.showOrderPrice()}
                        {this.confirmOrder()}
                    </View>
                }
                {this.showCouponModal()}
            </View>
        )
    }
}